﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;

using Kunlun.Models;
using Kunlun.BusinessLogic;
using Kaca.Core.Common;

namespace Kunlun.Areas.Store.Controllers
{
    public class FrameController : Controller
    {

        KunLunEntities entities = new KunLunEntities();

        //框画首页
        public ActionResult Default()
        {
             try
            {
                var cheapList = KunlunProduct.GetInputProduct(86, 8); //6件特价产品
                var firstList = KunlunProduct.GetInputProduct(87, 8); //某一类推荐产品
                var secondList = KunlunProduct.GetInputProduct(88, 8);
                var threeList = KunlunProduct.GetInputProduct(89, 8);

                var newsList = KunLunInformation.GetNewsByChanel("frame", 8);

                ViewData["cheap"] = cheapList;
                ViewData["first"] = firstList;
                ViewData["second"] = secondList;
                ViewData["three"] = threeList;

                ViewData["News"] = newsList;

                var adList = KunLunInformation.getAdByChanel("frame");

                return View(adList);
            }
            catch (Exception ex)
            {
                WebLog.ErrorLog(ex);
                 return View();
            
            }
        }

        public ActionResult CategoryMenu(int? id)
        {
            var menuList = KunlunCategory.GetCategoryMenuList();
			ViewData["CateID"] = id.Value;
            return PartialView("CategoryMenu", menuList);
        }

        public ActionResult Index(int id)
        {

            List<Product> product = KunlunProduct.GetProductByCategoryID(id.ToString());

            ViewData["Category"] = KunlunCategory.GetListByParentID(id);

            return View(product);
        }

        #region 产品详细页

        public ActionResult Views(string id)
        {
            var product = KunlunProduct.GetProductByID(id);
            ViewData["menulist"] = product.Categorys;
            WriteHisCookie(id);
            if (product.Products == null)
            {
                var err = new System.Web.Mvc.HandleErrorInfo(new Exception("没有找到您需要的产品!"), "Frame", "Views");
                Response.StatusCode = 404;

                return View("Error", err);
            }
            return View(product);
        }

        /// <summary>
        /// 读取写入游览过商品记录
        /// </summary>
        /// <param name="pid">产品id</param>
        /// <returns>返回浏览过的商品记录</returns>
        public void WriteHisCookie(string curpid)
        {
			HttpCookie cookie = KunlunCookies.GetHisCookis();
			string[] proIDs = cookie.Value.Split(',');
			if (!proIDs.Contains(curpid)) {
				cookie.Value += "," + curpid;
			}
			KunlunCookies.ResetCookis(cookie);
        }

		public ActionResult ReadHisCookie() {
			StringBuilder sb = new StringBuilder();
			sb.Append("<dl><dt>浏览的商品</dt>");
			HttpCookie cookie = KunlunCookies.GetHisCookis();
			string[] proIDs = cookie.Value.Split(',');
			for (int i = proIDs.Length - 1; i >= 0 && i>proIDs.Length -6; i--) {

				if (string.IsNullOrEmpty(proIDs[i])) {
					break;
				}
				Product pro = KunlunProduct.GetProductModel(proIDs[i]);
				if (pro != null) {
					string tourl = Url.Action("Views", "Frame", new { id = pro.pid });
					string imgurl = WebLog.ImageHttp + Kunlun.BusinessLogic.ProductImageToThum.Thumbnail(pro.ViewPic);
					sb.Append("<dd>");
					sb.AppendFormat("<a href='{0}' class='img'><img onload='DrawImage(this,204,204)' src=\"{1}\" alt=\"{2}\" /></a>", tourl, imgurl, pro.Name);
					sb.AppendFormat("<a href='{0}'>{1}</a>", tourl, pro.Name);
					sb.Append("</dd>");
				}
			}

			sb.Append("</dl>");
			return Content(sb.ToString());
		}

        /// <summary>
        /// 当前产品的相关产品集合
        /// </summary>
        /// <param name="cid">当前产品的类别</param>
        public PartialViewResult RelationProduct(string cid)
        {
            var model = KunlunProduct.GetRelationProduct(cid, 6);
            return PartialView(model);
        }

        #endregion

        public ActionResult ChildCategory(int id)
        {
            List<Category> category = KunlunCategory.GetListByParentID(id);
            return PartialView(category);
        }

        #region 类别列表页

        public ActionResult List(int id)
        {
            var model = KunlunCategory.GetCategortByTwo(id);

            //var model = KunlunCategory.GetModel(cid);
            return View(model);
        }

        #endregion

        #region 类别更多页

        public ActionResult MoreList(int? id, int? page)
        {
            PageModel model = new PageModel();
            page = page ?? 1;

            id = id ?? 0;

            //-----条件------
            Dictionary<string, object> where = new Dictionary<string, object>();
            where.Add("ClassID", id.Value);

            int count; 
            int pageindex = Convert.ToInt32(page - 1);
            model.PageIndex = pageindex;
            model.PageSize = 20;

            var plist = KunlunProduct.GetProductPageList(0, 20, where, out count);

            model.ItemCount = count;

            ViewData["catemunulist"] = KunlunCategory.GetMoreListMenu(12, 4);
            ViewData["menulist"] = KunlunProduct.GetMenuList(id.Value);
            //ViewData["readcookie"] = ReadCookie();

            ViewBag.Page = model;
            return View(plist);
        }


        #endregion

        #region 索引页

        /// <summary>
        /// 搜索产品
        /// </summary>
        public ActionResult Search()
        {
			int showtype;
			if (!int.TryParse(Request.QueryString["Classid"], out showtype)) {
				showtype = 38;
			}
            ViewData["HisCates"] = KunlunCategory.GetListByParentID(38, false, "SearchHisCates");
            ViewData["Cates"] = KunlunCategory.GetListByParentID(showtype, true, "SearchCates");
	

			List<Category> cates = new List<Category>();
			Category tcate = KunlunCategory.GetModel(showtype);
			while (tcate != null && tcate.ID != 38 && tcate.ID != 0) {
				
				cates.Insert(0,tcate);
				showtype = tcate.ParentID;
				tcate = KunlunCategory.GetModel(showtype);
			} 

			ViewData["TreeCate"] = cates;
            Dictionary<string, object> where = new Dictionary<string, object>();

			foreach (string key in Request.QueryString) {
				if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(Request.QueryString[key])) {
					where.Add(key, Request.QueryString[key]);
				}
			}
			if (!where.ContainsKey("Classid")) {
				where.Add("Classid", 38);
			}


			int index = 0;
			int.TryParse(Request.QueryString["index"], out index);
			int count;
			ViewData["Index"] = index;
			ProductSort sort = ProductSort.上架新品;
			if (!string.IsNullOrEmpty(Request.QueryString["sort"])) {
				int sortID;
				if (int.TryParse(Request.QueryString["sort"], out sortID)) {
					sort = (ProductSort)sortID;
				}
			}

			var plist = KunlunProduct.GetProductPageList(index, 12, where, sort, out count);
			ViewData["GoodsCount"] = count;
            return View(plist);
        }

        #endregion
    }
}
